package com.wtwd.campus.method;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.entity.VerifyResult;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.Sha256Utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.TreeMap;

/**
 * @Author ldaoliang
 * @Date create in 10:30 2021/7/5
 * @Description
 */
public class DeleteEncrypt implements EncryptVerify {

    @Override
    public VerifyResult verify(String sign, String token, HttpServletRequest request, RedisService redisService) {
        String requestUrl = request.getRequestURI();
        String encryptParam = requestUrl.substring(requestUrl.lastIndexOf("/") + 1);
        // 删除请求
        Enumeration<String> parameterNames = request.getParameterNames();
        TreeMap<String, String> treeMap = new TreeMap();
        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            treeMap.put(name, request.getParameter(name));
        }
        // 如果为空
        if (!treeMap.isEmpty()) {
            JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(treeMap), Feature.OrderedField);
            encryptParam = encryptParam.concat(json.toJSONString());
        }
        // 加密判断
        if (!Sha256Utils.SHA256(token + encryptParam).equalsIgnoreCase(sign)) {
            VerifyResult verifyResult = new VerifyResult();
            verifyResult.setResult(false);
            verifyResult.setRespCode(RespCode.REQUEST_ILLEGAL);
            return verifyResult;
        }
        return null;
    }
}
